package com.bawei.module_motocircle.ui.post

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.RecycledViewPool
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.Router
import com.bawei.lib_common.base.BaseFragment
import com.bawei.lib_common.base.state.Empty
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.IRetryClickListener
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.Success
import com.bawei.lib_common.base.state.UILoader
import com.bawei.lib_common.base.state.UIState
import com.bawei.lib_common.observeWithLifecycle
import com.bawei.lib_common.utils.LoggerUtils
import com.bawei.lib_common.utils.ToastUtils
import com.bawei.lib_storage.mmkv.AuthMMKV
import com.bawei.module_motocircle.R
import com.bawei.module_motocircle.databinding.FragmentPostListBinding
import com.bawei.module_motocircle.databinding.LayoutRefreshRecyclerviewBinding
import com.bawei.module_motocircle.helper.LikeGifAnimHelper2
import com.bawei.lib_common.video.VideoRecyclerViewHelper
import com.bawei.module_motocircle.databinding.LayoutItemPostListBinding
import com.bawei.module_motocircle.model.PostItem
import com.bawei.module_motocircle.ui.post.adapter.PostListAdapter
import com.bawei.module_motocircle.ui.post.adapter.PostViewHolder
import com.google.android.exoplayer2.util.MimeTypes
import dagger.hilt.android.AndroidEntryPoint

/**
 * 帖子列表
 */
@AndroidEntryPoint
class PostListFragment : BaseFragment<PostListViewModel, FragmentPostListBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.fragment_post_list

    private val mVieModel: PostListViewModel by viewModels()
    //点赞gif动画
    val helper by lazy {
        LikeGifAnimHelper2(requireActivity())
    }
    //视频播放帮助类
    private val mVideoRecyclerViewHelper by lazy {
        object : VideoRecyclerViewHelper() {
            override fun getVideoUrl(position: Int): String? {
                return mPostListAdapter.getPostItem(position)?.image?.firstOrNull()?.url
            }

            override fun isVideo(position: Int): Boolean {
                return MimeTypes.isVideo(mPostListAdapter.getPostItem(position)?.image?.firstOrNull()?.contentType)
            }

            override fun getVideoContainer(viewHolder: RecyclerView.ViewHolder): FrameLayout? {
                if (viewHolder !is PostViewHolder) {
                    return null
                }
                val binding = DataBindingUtil.getBinding<LayoutItemPostListBinding>(viewHolder.itemView)
                return binding?.lVideo
            }

            override fun getVideoCoverView(viewHolder: RecyclerView.ViewHolder): ImageView? {
                if (viewHolder !is PostViewHolder) {
                    return null
                }
                val binding = DataBindingUtil.getBinding<LayoutItemPostListBinding>(viewHolder.itemView)
                return binding?.ivVideo
            }

            override fun getVideoIcon(viewHolder: RecyclerView.ViewHolder): View? {
                if (viewHolder !is PostViewHolder) {
                    return null
                }
                val binding = DataBindingUtil.getBinding<LayoutItemPostListBinding>(viewHolder.itemView)
                return binding?.ivPlay
            }

            override fun getVideoLoadingView(viewHolder: RecyclerView.ViewHolder): View? {
                if (viewHolder !is PostViewHolder) {
                    return null
                }
                val binding = DataBindingUtil.getBinding<LayoutItemPostListBinding>(viewHolder.itemView)
                return binding?.loading
            }
        }
    }
    private val mPostListAdapter by lazy {
        PostListAdapter(
            onLikeClick = {postItem, i ->

            },
            onLikeViewClick = {postItem, i, view ->
                if(!AuthMMKV.hasLogin()){
                    return@PostListAdapter
                }
                //优化：开启gif动画
                if (postItem.if_like == 0) {
                    helper.setTargetView(view)
                    helper.startGif()
                }
                //优化：本地先更新UI，再发起网络请求，若失败回滚UI状态
                updateLike(postItem)
                //点赞
                mVieModel.giveLike(postItem.posts_id,i)

            },
            onCommentsClick = {

            },
            onShareClick = {

            },
            onFollowViewClick = {postItem, i, view ->

            },
            onCollectionViewClick = {postItem, i, view ->

            },
            onMoreActionClick = {postItem, i ->

            },
            onItemClick = {postItem, i ->
                ARouter.getInstance().build(Router.Ui.PostDetailsActivity).navigation()

            },
            onUserClick =  {postItem ->

            },
            showRelationState = ifFocus == 0  //是否显示关系
        )
    }

    private fun updateLike(postItem: PostItem) {
       if(postItem. if_like == 0){
           postItem.if_like = 1
           postItem.like_number ++
       }else{
           postItem.if_like = 0
           postItem.like_number --
       }
       mPostListAdapter.updatePostItem(postItem)
    }

    //分页参数
    private var ifFocus: Int? = null
    private var keyword: String? = null
    private var memberId: String? = null
    private var topicId: String? = null
    private var sortBy: String? = null

    companion object {
        private const val KEYWORD = "keyword"
        private const val SORT_BY = "sort_by"
        private const val MEMBER_ID = "member_id"
        private const val IF_FOCUS = "IF_FOCUS"
        private const val TOPIC_ID = "topic_id"
        fun newInstance(
            ifFocus: Int? = null,
            keyword: String? = null,
            memberId: String? = null,
            topicId: String? = null,
            sortBy: String? = null
        ): PostListFragment {
            val postListFragment = PostListFragment()
            postListFragment.arguments = Bundle().apply {
                putInt(IF_FOCUS, ifFocus ?: 0)
                putString(KEYWORD, keyword)
                putString(MEMBER_ID, memberId)
                putString(TOPIC_ID, topicId)
                putString(SORT_BY, sortBy)
            }
            return postListFragment
        }
    }

    override fun initView() {
        ifFocus = arguments?.getInt(IF_FOCUS)
        keyword = arguments?.getString(KEYWORD)
        memberId = arguments?.getString(MEMBER_ID)
        topicId = arguments?.getString(TOPIC_ID)
        sortBy = arguments?.getString(SORT_BY)
        initUILoader()
        initAdapter()

    }

    /**
     * 初始化适配器
     */
    private fun initAdapter() {
        mContentBinding.rv.adapter = mPostListAdapter
        mContentBinding.rv.layoutManager = LinearLayoutManager(requireContext())
        mContentBinding.rv.setHasFixedSize(true)
        mContentBinding.rv.setItemViewCacheSize(10)
        val pool = RecycledViewPool()
        pool.setMaxRecycledViews(0,10)
        mContentBinding.rv.setRecycledViewPool(pool)

        //视频帮助类
        mVideoRecyclerViewHelper.init(
            requireActivity(), mContentBinding.rv,
            onPlayingVideoClick = null,
            onNotPlayingVideoClick = null
        )

    }

    /**
     * 暂停播放
     */
    override fun onPause() {
        super.onPause()
        mVideoRecyclerViewHelper.pausePlayer()
    }

    /**
     * 恢复播放
     */
    override fun onResume() {
        super.onResume()
        if (isVisible)
            mVideoRecyclerViewHelper.startPlayer()
        else
            mVideoRecyclerViewHelper.hidePlayerView()
    }
    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            mVideoRecyclerViewHelper.startPlayer()
        } else {
            mVideoRecyclerViewHelper.pausePlayer()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mVideoRecyclerViewHelper.releasePlayer()
    }

    private lateinit var mContentBinding: LayoutRefreshRecyclerviewBinding
    private lateinit var mUiLoader: UILoader

    /**
     * 初始化全局状态
     */
    private fun initUILoader() {
        mContentBinding = DataBindingUtil.inflate(
            LayoutInflater.from(context),
            R.layout.layout_refresh_recyclerview,
            null,
            false
        )
        mUiLoader = object : UILoader(requireContext()) {
            override fun loadSuccessView(container: ViewGroup?): View {
                return mContentBinding.root
            }
        }.apply { updateState(UIState.LOADING) }

        mUiLoader.onLoginClick = {
//            ARouterUtils.jumpLogin(requireActivity() as? AppCompatActivity)
        }
        mUiLoader.setOnRetryClickListener(object : IRetryClickListener {
            override fun onRetryClick() {

            }
        })
        mBinding.layoutContent.addView(mUiLoader)

    }

    override fun initData() {
        //是否为关注页面
        if (ifFocus == 1){
            if (!AuthMMKV.hasLogin()){ //未登陆
                mUiLoader.updateState(UIState.UN_LOGIN)
            }else{//已登陆  是否有关注人
                mVieModel.checkIfHasFocus()
            }
        }else{
            //直接加载帖子数据
            getPostListData()
        }
    }
    fun getPostListData(){
        //设置参数
        mVieModel.setPageParam(sortBy, topicId,memberId,ifFocus,topicId)
        //网络请求数据
        mVieModel.pageList()
        //订阅帖子数据：防止每次直接订阅显示加载中
        observePostData()
    }

    override fun initListener() {
        //判断是否有关注的人
        mVieModel.mCheckIfHasFocus.observe(this){
           if (it == true){
               //直接加载帖子数据
               getPostListData()
           }else{
                mUiLoader.updateState(UIState.NO_FOLLOW)
           }
        }
        //点赞结果
        mVieModel.requestLikeEvent_.observeWithLifecycle(this){
            //点赞成功 不做处理
            //点赞失败 换回来
            if (it == -1){
                mPostListAdapter.getItemByPosition(it)?.let {
                    updateLike(it)
                }
            }

        }
    }

    fun observePostData(){
        mVieModel.mPostState.observeWithLifecycle(this){
            when(it){
                is Loading -> {
                    mUiLoader.updateState(UIState.LOADING)
                }
                is Success -> {
                    mUiLoader.updateState(UIState.SUCCESS)
                    //添加数据源更新UI
                    mPostListAdapter.setData(mVieModel.mPostListData)
                }
                is Failed -> {
                    mUiLoader.updateState(UIState.NETWORK_ERROR)
                    ToastUtils.showShort(requireActivity(),it.message)
                    LoggerUtils.d("TAG","加载失败"+it.message)
                }
                is Empty -> {
                    mUiLoader.updateState(UIState.EMPTY)
                }

                else -> {}
            }
        }
    }




}